package com.leyou.auth.config;

import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.auth.utils.JwtUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


public class MvcConfiguration implements WebMvcConfigurer {

    private JwtUtils jwtUtils;

    private ClientProperties clientProperties;


    /**
     * 在拦截器中初始化的Bean对象，是在拦截器之后生成的，
     * 所以如果我们不将其更改为懒加载，拦截器初始化就无法获取此对象，就会报错。
     * 所以我们需要加上@Lazy注解
     * @param jwtUtils
     * @param clientProperties
     */
    public MvcConfiguration(@Lazy JwtUtils jwtUtils, ClientProperties clientProperties) {
        this.jwtUtils = jwtUtils;
        this.clientProperties = clientProperties;
    }


    //添加拦截器到springMvc中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //注册拦截器，并得到拦截器注册器
        InterceptorRegistration interceptorRegistration =
                registry.addInterceptor(new LoginInterceptor(jwtUtils));


        // 判断用户是否配置了拦截路径，如果没配置走默认，就是拦截 /**
        if(!CollectionUtils.isEmpty(clientProperties.getIncludeFilterPaths())){
            interceptorRegistration.addPathPatterns(clientProperties.getIncludeFilterPaths());
        }
        // 判断用户是否配置了放行路径，如果没配置就是空
        if(!CollectionUtils.isEmpty(clientProperties.getExcludeFilterPaths())){
            interceptorRegistration.excludePathPatterns(clientProperties.getExcludeFilterPaths());
        }
    }
}
